<template>
  <div>
    <loading v-if="isShowLoading"></loading>
    <div v-if="choose_type == 0 && !isShowLoading">
      <header-tilte :title="title"></header-tilte>
      <p class="warnning"><i class="fa fa-bell-o"></i>请填写您的地址信息</p>
      <mu-container class="flex_center margin_top">
        <mu-form ref="form" :model="address" :label-position="labelPosition" class="mu-demo-form" >
          <div class="write_bac border-rad padding address_content">
            <mu-form-item label="用户姓名" prop="name" :rules="nameRules" class="margin_bom0">
              <mu-text-field v-model="address.name" prop="name" placeholder="请填写姓名"></mu-text-field>
            </mu-form-item>
            <mu-form-item label="联系电话" prop="mobile" :rules="mobileRules" class="margin_bom0">
              <mu-text-field type="text" v-model="address.mobile" prop="mobile" placeholder="请填写联系电话"></mu-text-field>
            </mu-form-item>
            <!--<router-link :to="{path: '/qds/mapChooseAddress', query: {id:id,type:type}}">-->
            <div @click="toMapChooseAddress()" style="display: none">
              <mu-form-item label="所属地区" prop="area_info" :rules="area_infoRules" class="margin_bom0">
                <mu-text-field type="text" v-model="address.area_info" prop="area_info"></mu-text-field>
              </mu-form-item>
            </div>
            <div @click="toMapChooseAddress()">
              <mu-form-item label="地址" prop="area_info" :rules="position_address_infoRules" class="margin_bom0">
                <mu-text-field type="text" v-model="address.position_address" prop="position_address" placeholder="请填写地址"></mu-text-field>
              </mu-form-item>
            </div>
            <!--</router-link>-->
            <mu-form-item label="门牌号" prop="address" :rules="addressRules" class="margin_bom0">
              <mu-text-field type="text" v-model="address.address" prop="address" placeholder="例：10号楼5层501室"></mu-text-field>
            </mu-form-item>
            <mu-form-item label="用户类型" prop="type" :rules="typeRules" class="margin_bom0">
              <mu-radio v-model="address.type" value='1' label="单位"></mu-radio>
              <mu-radio v-model="address.type" value='2' label="家庭"></mu-radio>
            </mu-form-item>
            <mu-form-item label="单位简称" prop="company_name" :rules="company_nameRules" v-if="address.type == 1">
              <mu-text-field type="text" v-model="address.company_name" prop="company_name" placeholder="请填写单位简称"></mu-text-field>
            </mu-form-item>
          </div>
          <mu-form-item class="address_button">
            <mu-button color="primary" @click="submit">提交</mu-button>
          </mu-form-item>
        </mu-form>
      </mu-container>
    </div>
    <map-choose-address :mapAddress="mapAddress" :region="region" v-if="choose_type == 1" v-on:mapSearch="mapSearch" v-on:getMapAddress="getMapAddress" v-on:getregion="getregion"></map-choose-address>
    <search-address-list :mapAddress="mapAddress" :region="region" v-if="choose_type == 2" v-on:mapSearch="mapSearch" v-on:getMapAddress="getMapAddress" v-on:getregion="getregion"></search-address-list>
  </div>
</template>
<script>

  import HeaderTilte from "../../components/headerTilte";
  import Rules from '../../components/Rules';
  import MapChooseAddress from "../../components/personal/components/MapChooseAddress";
  import SearchAddressList from "../../components/personal/components/SearchAddressList";
  import Loading from "../../components/loading";
  export default {
    components: {
      Loading,
      MapChooseAddress,
      SearchAddressList,
      HeaderTilte,
    },
    data () {
      return {
        isShowLoading:true,
        from_type:0,//表示当前操作从哪里来 0:表示从地址列表  1：表示从订单页面 2:表示从一件订水处来
        position: 'top',
        labelPosition: 'left',
        title:'新增地址',
        toType:'',//0 表示编辑 1表示新增
        address: {
          id:'',
          name:'',
          mobile:'',
          area_info:'',
          address:'',
          position_address:'',
          type:'1', //1 单位 2家庭
          company_name:'',
          area_position:'',
          province_id:'',
          area_id:'',
          city_id:'',
          range_in:'1' //1表示在配送范围 0 或null 等不在配送范围
        },
        addressDetail:'',
        searchCity:'',
        choose_type:0,
        region:'',
        mapAddress:{
          area_position:'',//经纬度-字符串
          area_info:'',//省市区
          address:'',//详细地址
          province_id:'',
          city_id:'',
          area_id:'',
        },
        nameRules: [
          { validate: (val) => !!val, message: '请填写用户名'},
          { validate: (val) => val.length >= 1 && val.length <=5, message: '用户名长度大于3或者小于5'}
        ],
        mobileRules: [
          { validate: (val) => Rules.required(val), message: '请填写手机号'},
          { validate: (val) => Rules.phone(val), message: '手机号格式错误'},
        ],
        area_infoRules :[
          { validate: (val) => Rules.required(val), message: '请选择所属地区'},
        ],
        position_address_infoRules:[
          { validate: (val) => Rules.required(val), message: '请填写地址'},
        ],
        addressRules: [
          { validate: (val) => Rules.required(val), message: '请填写详细地址'},
        ],
        typeRules: [
          { validate: (val) => Rules.required(val), message: '请选择用户类型'},
        ],
        company_nameRules: [
          { validate: (val) => Rules.checkChoose(val,this.address.type,1),message:'请填写单位简称' }
        ],
      }
    },
    mounted(){
      this.checkLogin();
      this.initH();
      var id = this.$route.query.id;
      if(!this.isEmpty(id)){
        this.toType = 0;
        this.title = '编辑地址';
        this.initAddress(id);
      }else {
        this.isShowLoading = false;
        this.toType =1;
      }

      this.$nextTick(function () {
        $('.mu-text-field-input').addClass('addclass_adress');
        $('.mu-radio-label').css('font-size','0.9rem')
      })
      this.from_type = this.$route.query.type;//表示当前操作从哪里来 0:表示从地址列表  1：表示从订单页面 2:表示从一件订水处来

    },
    methods: {
      initH(){
        var headerH = $('.header').outerHeight(true);
        var allH = document.documentElement.clientHeight;
        var footH = $('.address_button').height();
        var wH = $('.warnning').height();
        var h = allH - headerH - footH - wH;
        $('.address_content').css('height',h+'px');
      },
      initAddress(id){
        var _lsef = this;
        if(id != undefined && id != null && id!= ''){
          this.yesS.getAddressDetail(this.$combineParams({
            id:id
          })).then(res => {
            this.address = res.data.info;
            var areainfo = '';
            if(this.address.area_info[0]){
              areainfo = this.address.area_info[0];
            }
            if(this.address.area_info[1]){
              areainfo += ' '+this.address.area_info[1];
            }
            if(this.address.area_info[2]){
              areainfo += ' '+this.address.area_info[2];
            }
            this.address.area_info = areainfo;
            this.address.type = this.address.type+'';
            //判断是否在配送范围
            var center = this.address.area_position;
            if(!this.isEmpty(center)){
              this.checkRange(center,0);
            }
            this.isShowLoading = false;
          })

        }
      },


      toMapChooseAddress(){
        this.mapAddress.area_position = this.address.area_position;
        this.mapAddress.address = this.address.position_address + this.address.address;
        this.mapAddress.area_id = this.address.area_id;
        this.mapAddress.city_id = this.address.city_id;
        this.mapAddress.province_id = this.address.province_id;
        this.mapAddress.area_info = this.address.area_info;
        this.choose_type = 1;
      },


      //显示哪个页面 0主页面 1地图页面 2地址搜索页面
      mapSearch: function (childValue) {
        // childValue就是子组件传过来的值
        this.choose_type = childValue;
      },
      //获取地图或地址搜索页面的相关信息
      getMapAddress:function (childValue) {
        // childValue就是子组件传过来的值
        this.mapAddress = childValue;
        this.address.province_id = this.mapAddress.province_id;
        this.address.city_id = this.mapAddress.city_id;
        this.address.area_id = this.mapAddress.area_id;
        this.address.area_info = this.mapAddress.area_info;
        this.address.position_address = this.mapAddress.address;
        this.address.area_position = this.mapAddress.area_position;
        if(!this.isEmpty(this.address.area_position)){
          this.checkRange(this.address.area_position,1);
        }

      },

      //获取当前所在市
      getregion:function (childValue) {
        this.region = childValue;
      },
      //判断是否在配送范围
      checkRange(latLng,type){
        var latLng = latLng.split(',');
        latLng = new qq.maps.LatLng(latLng[0],latLng[1]);

        this.address.range_in = 1;
        this.yesS.getShopInfo(
          this.$comParams()
        ).then(res => {
          var choose_center = res.data.info.shop_position;
          var range_height = res.data.info.send_area_radius * 1000;
          //如果choose_center 不为空，判断是否在配送范围内
          if(choose_center != undefined && choose_center != '' && choose_center != null
            && range_height != undefined && range_height != null &&range_height != ''){

            choose_center = choose_center.split(',');
            var shop_add = new qq.maps.LatLng(choose_center[0],choose_center[1]);

            var length = qq.maps.geometry.spherical.computeDistanceBetween(shop_add, latLng);
            if(length >range_height){
              if(type == 1){
                this.$toast.warning('超出配送范围，请重新选择配送地址');
              }
              this.address.range_in = 0;
            }
          }
        })
      },

      toAddressList(){
        if(this.isEmpty(this.from_type) || this.from_type == 0){
          this.$router.push({path:'/qds/addressList'})
        }
        if( this.from_type == 1){
          this.$router.push({path:'/qds/buildOrder'})
        }
        if(this.from_type == 2){
          this.$router.push({path:'/qds/bookingWater'})
        }

      },
      submit () {
        //判断是否在配送范围
        var rangeIn = this.address.range_in;
        if(!this.isEmpty(rangeIn) && rangeIn != 1){
          this.$toast.error('您所选地址不在配送范围，请重新选择地址');
          return;
        }
        this.$refs.form.validate().then((result) => {
          if(result == true){//验证通过

            var _lsef = this;
            var address = this.address
            this.yesS.addEditAddress(this.$combineParams(
              {id:address.id,
                name:address.name,
                mobile:address.mobile,
                area_info:address.area_info,
                address:address.address,
                position_address:address.position_address,
                type:address.type, //1 单位 2家庭
                company_name:address.company_name,
                area_position: address.area_position,//address.area_position,
                province_id: address.province_id,//address.province_id,
                area_id: address.area_id,//address.area_id,
                city_id: address.city_id,//address.city_id,
                range_in:'',}
            )).then(res => {
              setTimeout(function () {
                if(_lsef.isEmpty(_lsef.from_type)|| _lsef.from_type == 0){
                  _lsef.$router.push({path:'/qds/addressList'})
                }
                if( _lsef.from_type == 1){
                  _lsef.$router.push({path:'/qds/buildOrder'})
                }
                if(_lsef.from_type == 2){
                  _lsef.$router.push({path:'/qds/bookingWater'})
                }

              },1000)
            })
          }
        });
      },
      clear () {
        this.$refs.form.clear();
        this.address = {
          username: '',
          password: '',
          isAgree: false
        };
      },
    },
    watch:{
      //监听地址变化
      address:{
        handler(curVal,oldVal){
          /*this.addressDetail = curVal.address;*/
          this.setCache('addressItem', JSON.stringify(this.address))
        },
        deep:true
      },
      addressDetail:{ //填写详情地址时重新获取经纬度  -- 现在不用了
        /*handler(curVal,oldVal){
          //获取经纬度 和 是否在配送范围
          //根据已有地址获取经纬度
          if(oldVal != undefined && oldVal != null && oldVal != ''){
            if(oldVal != curVal){
              //获取当前地址的经纬度和判断是否在配送范围
              console.log('2222')
              var _self = this;
              var infos = this.address.area_info +' '+ curVal;
              if(curVal == undefined || curVal == null || curVal == ''){
                return;
              }
              //根据已经有的地址获取经纬度
              //地址和经纬度之间进行转换服务
              var geocoder = new qq.maps.Geocoder({
                //设置服务请求成功的回调函数
                complete: function (result) {
                  var lat = result.detail.location.lat;
                  var lng = result.detail.location.lng;
                  _self.address.area_position = lat+','+lng;
                  _self.addressDetail = curVal;
                },
              });
              //如果没有经纬度 那么 按照店铺地址获取经纬度
              geocoder.getLocation(infos);
            }
          }
        },
        deep:true*/
      },
    },
  };
</script>
<style>
  @import "./css/addAddress.css";
  /*@import 'http://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.css';*/
  .mu-demo-form {
    width: 100%;
    max-width: 460px;
  }
  .mu-text-field-input{
    font-size: 0.9rem;
  }
  .margin_bom0{
    margin-bottom: 0!important;
  }

  .header{
    width: 100%;
    padding: 0.5rem;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    align-items: center;
    -webkit-align-items: center;
    border-bottom: 1px solid #c3c3c3;
    background: #fff;
    position: relative;
  }
  .header img{
    width: 1.25rem;
    height: 1.25rem;
  }
</style>
